<template>
  <d2-container
    v-loading="loading"
    style="margin-left: 10px; margin-right: 50px"
  >
    <el-card>
      <el-form
        ref="storeBillForm"
        class="normalForm"
        :rules="rulesList"
        :model="billVO"
        label-width="120px"
        size="small"
      >
        <div>
          <el-form-item label="采购供应商" prop="supplierId" class="fromBox">
            <el-select
              v-model="billVO.supplierId"
              filterable
              placeholder="请选择采购供应商"
            >
              <el-option
                v-for="item in checkPurchaseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="采购员" prop="purchaseUser" class="fromBox">-->
<!--            <el-select-->
<!--              v-model="billVO.purchaseUser"-->
<!--              filterable-->
<!--              placeholder="请选择采购员"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in userSelectList"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="采购大仓" prop="storeId" class="fromBox">
            <el-select
              v-model="billVO.storeId"
              filterable
              placeholder="请选择大仓"
            >
              <el-option
                v-for="item in firstStoreList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item
          v-if="type == 'edit'"
          label="状态"
          prop="status"
          style="clear: both"
        >
          <el-tag size="small">{{ purchaseStatus[billVO.status] }}</el-tag>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="clear: both">
          <el-input
            v-model="billVO.remark"
            style="width: 80%"
            type="text"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-collapse v-model="activeNames" style="clear: both">
        <el-collapse-item name="1">
          <template slot="title">
            <div style="margin-left: 10px">
              添加商品<i class="header-icon el-icon-info" />
            </div>
          </template>
          <el-row style="clear: both">
            <el-col :span="3">
              <el-input
                v-model="skuQueryData.name"
                placeholder="请输入商品名称"
                suffix-icon="el-icon-search"
                class="fromInputWidth"
                size="small"
                @input="onSearchShopInput"
              />
            </el-col>
          </el-row>
          <el-table
            :data="skuDetailList"
            border
            max-height="450px"
            size="mini"
            empty-text="暂无数据"
            stripe
            :header-cell-style="{
              background: '#f2f3f7',
              color: '#333',
              fontWeight: '500',
              textAlign: 'center',
            }"
            @cell-dblclick="
              (row) => {
                dbSelectTable(row)
              }
            "
          >
            <el-table-column prop="sku" label="商品code" />
            <el-table-column prop="spuName" label="商品名称" />
            <el-table-column prop="attributeDesc" label="商品属性" />
            <el-table-column prop="categoryName3" label="三级分类" />
            <el-table-column prop="categoryName2" label="二级分类" />
            <el-table-column prop="categoryName1" label="一级分类" />
          </el-table>
          <el-pagination
            small
            style="overflow: auto hidden; height: 32px; float: right"
            :current-page="skuPage.currPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="skuPage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="skuPage.totalCount"
            @size-change="skuPageSizeChange"
            @current-change="skuPageCurrentChange"
          />
        </el-collapse-item>
      </el-collapse>
      <el-table
        :data="billDetailVOList"
        size="mini"
        border
        :header-cell-style="{
          background: '#f2f3f7',
          color: '#333',
          textAlign: 'center',
        }"
        style="width: 100%"
      >
        <el-table-column width="100" label="操作" align="center">
          <template slot-scope="scope">
            <el-link
              style="font-size: 13px"
              type="primary"
              @click="delRow(scope.row)"
              >删除行</el-link
            >
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="商品编码" align="center" />
        <el-table-column prop="attributeDesc" label="商品属性" align="center" />
        <el-table-column prop="purchaseNum" label="采购数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.purchaseNum"
              controls-position="right"
              :min="1"
              :max="99999"
              size="mini"
              style="width: 110px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="unitCost" label="采购单价" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.unitCost"
              size="mini"
              placeholder="请输入采购单价"
            />
          </template>
        </el-table-column>
        <el-table-column prop="totalCost" label="采购总价" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.totalCost"
              size="mini"
              placeholder="请输入采购总价"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              size="mini"
              placeholder="请输入备注"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <span slot="footer" class="dialog-footer">
      <el-col :span="20" align="center">
        <el-button size="small" type="primary" @click="saveOrder()"
          >保存商品</el-button
        >
        <el-button size="small" @click="close()">取 消</el-button>
      </el-col>
    </span>
  </d2-container>
</template>

<script>
import api from '@/api'

export default {
  name: '',
  data() {
    return {
      loading: false,
      billVO: {},
      billDetailVOList: [],
      skuDetailList: [],
      type: 'add',
      addSkuDialog: false,
      checkPurchaseList: [],
      checkStoreList: [],
      firstStoreList: [],
      userSelectList: [],
      activeNames: [],
      purchaseStatus: {
        0: '待审核',
        1: '审核通过',
        2: '到货异常',
        3: '已完成',
        9: '已取消',
      },
      skuQueryData: {
        pageNum: 1,
        pageSize: 10,
      },
      skuPage: {
        currPage: 1,
        pageSize: 10,
        totalCount: 100,
      },
      rulesList: {
        // supplierId purchaseUser memberId
        supplierId: [
          { required: true, message: '请选择采购供应商', trigger: 'blur' },
        ],
        // purchaseUser: [
        //   { required: true, message: '请选择采购员', trigger: 'blur' },
        // ],
        memberId: [
          { required: true, message: '请选择所属客户', trigger: 'blur' },
        ],
        storeId: [
          { required: true, message: '请选择采购大仓', trigger: 'blur' },
        ],
        // 'spuEntity.name': [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        // 'spuEntity.brandId': [{ required: true, message: '请选择品牌', trigger: 'blur' }],
        // 'spuEntity.unitId': [{ required: true, message: '请选择单位', trigger: 'blur' }],
        // 'spuEntity.channel': [{ required: true, message: '请选择销售渠道', trigger: 'blur' }]
      },
    }
  },
  created() {
    this.loading = true
    this.getStaticOrderData()
    const query = this.$route.query
    if (query.type === 'edit') {
      // // 清除延迟执行
      // clearTimeout(this.timer)
      // // 设置延迟执行
      // this.timer = setTimeout(() => {
      this.getPurchaseBillDetail(query.id)
      // }, 2000)
      this.type = 'edit'
    }
    this.getShopSkuList()
  },
  methods: {
    getStaticOrderData() {
      api.STOCK_PURCHASE_SUPPLIER({ status: true }).then((res) => {
        this.checkPurchaseList = res
      })
      api.STOCK_PURCHASE_AGENT().then((res) => {
        this.userSelectList = res
      })
      // stockPurchaseAgentSelectList().then((res) => {
      //   this.userSelectList = res
      // })
      api.STOCK_PURCHASE_STORE().then((res) => {
        this.firstStoreList = res
      })
    },
    getPurchaseBillDetail(billId) {
      getPurchaseBillDetail({ id: billId }).then((res) => {
        debugger
        this.billVO = res
        this.billDetailVOList = res.detail
        const temp = this.billVO.storeArr.split(',')
        const storeIdArr = []
        for (const t of temp) {
          storeIdArr.push(Number(t))
        }
        this.billVO.storeArr = storeIdArr
      })
    },
    afterAddSkuDialog() {},
    addBillDetailMethod() {},
    handleClose() {
      this.type = 'add'
      this.billVO = {}
      this.billDetailVOList = []
    },
    checkStore(value) {
      if (value == null || value.length === 0) {
        return
      }
      this.billVO.storeId = value[value.length - 1]
    },
    addSku() {
      this.getShopSkuList()
      this.addSkuFlag = true
      this.addSkuDialog = true
    },
    delRow(row) {
      this.billDetailVOList.splice(this.billDetailVOList.indexOf(row), 1)
    },
    skuPageSizeChange(val) {
      this.skuQueryData.pageSize = val
      this.getShopSkuList()
    },
    skuPageCurrentChange(val) {
      this.skuQueryData.pageNum = val
      this.getShopSkuList()
    },
    getShopSkuList() {
      api.STOCK_PURCHASE_SKULIST(this.skuQueryData).then((res) => {
        this.skuDetailList = res.list
        this.skuPage.currPage = res.currPage
        this.skuPage.pageSize = res.pageSize
        this.skuPage.totalCount = res.totalCount
        this.loading = false
      })
    },
    onSearchShopInput() {
      clearTimeout(this.trime)
      this.trime = setTimeout(() => {
        this.getShopSkuList()
      }, 1000)
    },
    dbSelectTable(row) {
      for (const vo of this.billDetailVOList) {
        if (vo.sku === row.sku) {
          this.$message.error('该sku已存在,请勿重复添加!')
          return
        }
      }
      // attributeDesc
      const billDetailVO = {}
      billDetailVO.sku = row.sku
      billDetailVO.purchaseNum = 0
      billDetailVO.receiveNum = 0
      billDetailVO.unitCost = 0
      billDetailVO.totalCost = 0
      billDetailVO.attributeDesc = row.attributeDesc
      this.billDetailVOList.push(billDetailVO)
    },
    close() {
      this.handleClose()
      this.$store.dispatch('tagsView/delView', this.$route)
      // this.$router.push('/store/purchase/order/index')
      this.$router.go(-1)
    },
    saveOrder() {
      if (this.storeValid()) {
        return
      }
      this.$refs['storeBillForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.type === 'add') {
            api
              .STOCK_PURCHASE_ADD({
                storePurchaseBillSaveDTO: this.billVO,
                billDetailSaveDTOList: this.billDetailVOList,
              })
              .then((res) => {
                this.$message.success('添加成功')
                this.loading = false
                this.close()
              })
          } else {
            api
              .STOCK_PURCHASE_UPDATE({
                storePurchaseBillUpdateDTO: this.billVO,
                billDetailUpdateDTOList: this.billDetailVOList,
              })
              .then((res) => {
                this.$message.success('修改成功')
                this.loading = false
                this.close()
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    storeValid() {
      if (this.billDetailVOList.length === 0) {
        this.$message.error('采购商品不能为空')
        return true
      }
      return false
    },
  },
}
</script>

<style scoped>
.fromBox {
  float: left;
}
.fromInputWidth {
  width: 180px;
}
.el-col {
  margin: 10px;
}
</style>
